package log

import (
	"aria-go/exception"
	"aria-go/util"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"strings"
	"time"
)

type SimpleLogger struct {
	file *os.File
}

func (receiver *SimpleLogger) New(file interface{}) {
	switch file.(type) {
	case *os.File:
		receiver.newWithFile(file.(*os.File))
		break
	case string:
		receiver.newWithFileName(file.(string))
		break
	default:
		fmt.Println("不支持的文件类型")
	}
}

func (receiver *SimpleLogger) newWithFileName(fileName string) {
	if strings.Contains(fileName, "\\") {
		fileName = strings.ReplaceAll(fileName, "\\", "/")
	}

	if util.IsExist(fileName) {
		// 若存在日志文件则重命名
		newFileName := path.Dir(fileName) + util.DeleteFileSuffix(fileName) + time.Now().Format("2006-01-02") + path.Ext(fileName)
		if util.IsExist(newFileName) {
			err := os.Rename(fileName, newFileName)
			if err != nil {
				fmt.Println("日志文件重命名发生错误，错误信息：" + err.Error())
			}
		}
	}

	file, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
	if err != nil {
		panic("打开日志存储文件发生异常，进程终止。终止原因：" + err.Error())
	}

	receiver.newWithFile(file)
}
func (receiver *SimpleLogger) newWithFile(file *os.File) {
	receiver.file = file
	err := receiver.file.Close()
	if err != nil {
		fmt.Println("创建日志文件关闭文件句柄错误，错误原因："+err.Error())
	}

}
func (receiver *SimpleLogger) writeLog(level int, msg string, ex ...*exception.Exception) {
	var levelStr string

	switch level {
	case debug:
		levelStr = "debug"
		break
	case error:
		levelStr = "error"
		break
	case info:
		levelStr = "info"
		break
	default:
		levelStr = "info"
	}

	logStr := time.Now().Format("2006-01-02T15：04：05.000") + spiltStr + levelStr + spiltStr

	if ex != nil {
		for i := range ex {
			logStr = logStr + ex[i].GetMsg() + "\n"
		}
	} else {
		logStr = logStr + msg + "\n"
	}
	err := ioutil.WriteFile(receiver.file.Name(), []byte(logStr), 0644)
	if err != nil {
		fmt.Println("日志文件写入错误，错误原因："+err.Error())
	}
}
func (receiver SimpleLogger) Debug(msg string, ex ...*exception.Exception) {
	receiver.writeLog(debug, msg, ex...)

}

func (receiver SimpleLogger) Info(msg string, ex ...*exception.Exception) {
	receiver.writeLog(info, msg, ex...)
}
func (receiver SimpleLogger) Error(msg string, ex ...*exception.Exception) {
	receiver.writeLog(error, msg, ex...)
}
